package common;

import java.util.concurrent.*;
import java.util.logging.Logger;

/**
 * 并发操作相关工具类
 */
public class ConcurrencyUtil {
    private static final Logger logger = LogUtil.getLogger(ConcurrencyUtil.class.getName());

    /**
     * 创建虚拟线程执行器
     */
    public static Executor createVirtualThreadExecutor() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }

    /**
     * 创建命名的线程工厂
     */
    public static ThreadFactory createNamedThreadFactory(String prefix) {
        return r -> {
            Thread thread = Thread.ofVirtual().name(prefix + "-" + System.nanoTime()).unstarted(r);
            return thread;
        };
    }

    /**
     * 创建定时任务执行器
     */
    public static ScheduledExecutorService createScheduler(int corePoolSize, String namePrefix) {
        return Executors.newScheduledThreadPool(corePoolSize, createNamedThreadFactory(namePrefix));
    }

    /**
     * 安全地关闭执行器
     */
    public static void shutdownExecutor(ScheduledExecutorService executor) {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
